package com.wwwc.index.web.servlet;

import java.io.*;
import java.net.*;
import java.util.*;
import java.security.Security;
import java.security.Provider;
import javax.net.ssl.*;
import java.text.DecimalFormat;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;

import com.wwwc.util.web.*;

public class StockHotList {

    private String myUrl = null;
    private String urlReturnString = new String();
    private Vector urlReturnVector = new Vector(10);
    private Vector recordVectorUp    = new Vector(10);
    private Vector recordVectorDown  = new Vector(10);
    private Vector newTickVector = new Vector ();

    private String start_price_up = null;
    private String start_price_down = null;
    private String end_price_up = null;
    private String end_price_down = null;
    private String v_low_limit = null;
    private String v_up_limit = null;
    private String numb_results = null;
    private String exchange = "0";

    private StringBuffer process_message = new StringBuffer();

    public StringBuffer getRangeForm (String form_action, StringBuffer hidden_elements)
    {
	StringBuffer sb = new StringBuffer();
	sb.append("<form method=post action="+form_action+">");
	sb.append("<table cellSpacing=0 cellPadding=4 border=1 style='font-size: 10pt'>");
	sb.append("<tr><td colspan=10 align=center style='font-size: 14pt'>Stock Hot List Generator</td></tr>");
      
	sb.append("<tr><td align=center style='font-size: 12pt'>Up/Down");
	sb.append("<td colspan=4 align=center style='font-size: 12pt'>Price</td>");
	sb.append("<td colspan=4 align=center style='font-size: 12pt'>Volume</td>");
	sb.append("<td align=center style='font-size: 12pt'>Results</td>");
	sb.append("<tr>");
	
	sb.append("<td>Top Up</td>");
	sb.append("<td>Form:</td><td>"+MyHtml.getTextBox("up1","0.01","10","10")+"</td>");
	sb.append("<td>To:</td><td>"+MyHtml.getTextBox("up2","100","10","10")+"</td>");
	sb.append("<td>Low</td><td>"+MyHtml.getTextBox("uv1","1,000,000","10","10")+"</td>");
	sb.append("<td>High:</td><td>"+MyHtml.getTextBox("uv2","20,000,000","10","10")+"</td>");
	sb.append("<td>"+MyHtml.getTextBox("urst","10", "10", "10")+"</td>");
	sb.append("</tr>");
		    
	sb.append("<tr>");
	sb.append("<td>Top Down</td>");
	sb.append("<td>From:</td><td>"+MyHtml.getTextBox("dp1","0.01","10","10")+"</td>");
	sb.append("<td>To:</td><td>"+MyHtml.getTextBox("dp2","100","10","10")+"</td>");
	sb.append("<td>Low:</td><td>"+MyHtml.getTextBox("dv1","1,000,000","10","10")+"</td>");
	sb.append("<td>High:</td><td>"+MyHtml.getTextBox("dv2","20,000,000","10","10")+"</td>");
	sb.append("<td>"+MyHtml.getTextBox("drst","10", "10", "10")+"</td>");
	sb.append("</tr>");
	sb.append("<tr><td colspan=10 align=center height=40>");
	sb.append("<input type=submit value=Submit style='font-size: 8pt'>");
	sb.append("<input type=reset value=Reset style='font-size: 8pt'>");
	sb.append("</td></tr>");
	sb.append("</table>");
	sb.append(hidden_elements);
	sb.append("</form>");
	return sb;
    }
    /*
    public StringBuffer getStockHotListAdmin(String call_path, String id) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<TABLE cellSpacing=0 cellPadding=1 border=0 width=100%>");
	sbf.append("\n<TR>");
	sbf.append("\n<TD align=center bgcolor='#EEEEEE' style='BORDER-BOTTOM: 1px solid;'>");
	sbf.append("\n<A href=/servlet/MainBarServlet?sid="+sid+"&aid=ghotlist>");
	sbf.append("\n<img src=/images/add.gif border=0>");
	sbf.append("\n</A>");
	sbf.append("\n</TD>");
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");
	return sbf;
    }
    */

    public StringBuffer getHotListMessage () {
	StringBuffer sbf = new StringBuffer();
	/*
	    "<H3>This is a computer generated top up stock list</H3>"+
	    "<TABLE width=50%>"+
	    "<TR><TD>Top up</TD><TD>"+dt.getCurrentDate()+"</TD>"+
	    "<TD>"+dt.getCurrentTime()+"</TD></TR>"+
	    "<TR><TD>Price range </TD><TD>"+start_price_up+"</TD><TD>"+end_price_up+"</TD></TR>"+
	    "<TR><TD>Volume range</TD><TD>"+v_low_limit+"</TD><TD>"+v_up_limit+"</TD></TR>"+
	    "<TR><TD>Number of results</TD><TD>"+numb_results+"</TD><TD></TD></TR>"+
	    "<TR><TD>Exchange</TD><TD>"+exchange+"</TD><TD></TD></TR>"+
	    "</TABLE></CENTER></BODY></HTML>";
	*/
	return sbf;
    }

    public StringBuffer getHotList () {
	StringBuffer sbf = new StringBuffer();
	/*
	DecimalFormat td = new DecimalFormat("0.00");
	start_price_up   = request.getParameter("price_up_start");
	start_price_down = request.getParameter("price_down_start");
	end_price_up     = request.getParameter("price_up_end");
	end_price_down   = request.getParameter("price_down_end");
	v_low_limit      = request.getParameter("volume_low");
	v_up_limit       = request.getParameter("volume_high");
	numb_results     = request.getParameter("number_result");
	exchange         = request.getParameter("ex_change");

	Vector rvu = new Vector();
	Vector rvd = new Vector();

	if(getTopUpListData() ) {
	    rvu= getRecordVectorUp();
	}
	if(getTopDownListData()) {
	    rvd= getRecordVectorDown();
	}

	MyDateAndTime dt = new MyDateAndTime();
	RandomAccessFile gf = null;

	String title_head_up     =  "["+start_price_up+"--"+end_price_up+"]["+v_low_limit+"--"+v_up_limit+"]";
	String title_head_down   =  "["+start_price_down+"--"+end_price_down+"]["+v_low_limit+"--"+v_up_limit+"]";

	long submit_id =  System.currentTimeMillis();

	DataBaseAccess db = new DataBaseAccess();
	String query = null;

	StockRecord r = new StockRecord();
	Enumeration enum_up = rvu.elements();
	String tick      = null;
	String company   = null;
	String price     = null;
	String price_h   = null;
	String price_l   = null;
	String price_ch  = null;
	String volume    = null;
	String mkcap     = null;
	String indu_name = null;
	String title     = null;

	while (enum_up.hasMoreElements()) {
	    r = (StockRecord)enum_up.nextElement();
	    tick     = r.getTick();
	    company  = r.getName();
	    price    = r.getPrice();
	    price_h  = r.getHigh();
	    price_l  = r.getLow();
	    price_ch = r.getChange();
	    volume   = r.getVolume();
	    mkcap    = r.getMarkCap();
	    if(mkcap.equals("n/a")) {
		mkcap = "0";
	    }
	    indu_name= r.getIndustryName();
	    
	    if(!tick.equals("Symbol")) { 
		f_check = new File(SystemInfo.STOCK_CHART_HOME, tick+".jsp");
		if(!f_check.exists()) {
		    gchart.setDistDir(SystemInfo.STOCK_CHART_HOME);
		    gchart.setDataDir(SystemInfo.STOCK_DATA_HOME);
		    gchart.setTick(tick);
		    gchart.setTickSid();

		    ok = gchart.generateChart();
		    if(!ok) {
			out.println("Can not generate chart for:<B>"+tick+"</B>");
		    }
		}
		else {
		    ok = true;
		}

		if(ok) {
		    title =tick+"</A>&nbsp;Price[$"+price+"]"+
			"&nbsp[500m Cap Price["+
			td.format(((Double.parseDouble(price)*Long.parseLong(mkcap.replaceAll(",","")))/500000000))+"]"+
			"&nbspRange[$"+price_l+"-"+price_h+"]"+
			"&nbspValume["+volume+"]"+
			"&nbspMkCap["+mkcap+"]"+
			"&nbsp["+indu_name+"]";
		    
		    link2 = "<IFRAME src=/index/jsp/Stocks/Charts/"+tick+".jsp width=100% scrolling=yes height=100%>";
		}
		else {
		    link2 = "";
		    title = "Top Up ["+dt.getCurrentDate()+"]["+dt.getCurrentTime()+"]"+title_head_up;
		  

		}
	    }

	    Enumeration enum_down = rvd.elements();
	    while (enum_down.hasMoreElements()) {
		r = (StockRecord)enum_down.nextElement();
		tick = r.getTick();
		company  = r.getName();
		price    = r.getPrice();
		price_h  = r.getHigh();
		price_l  = r.getLow();
		price_ch = r.getChange();
		volume   = r.getVolume();
		mkcap    = r.getMarkCap();
		if(mkcap.equals("n/a")) {
		    mkcap = "0";
		}
		indu_name= r.getIndustryName();

		if(!tick.equals("Symbol")) {
		    title =tick+"</A>&nbsp;Price[$"+price+"]"+
			"&nbsp[500m Cap Price["+
			td.format(((Double.parseDouble(price)*Long.parseLong(mkcap.replaceAll(",","")))/500000000))+"]"+
			"&nbspRange[$"+price_l+"-"+price_h+"]"+
			"&nbspValume["+volume+"]"+
			"&nbspMkCap["+mkcap+"]"+
			"&nbsp["+indu_name+"]";

		    link2 = "<IFRAME src=/index/jsp/Stocks/Charts/"+tick+
			".jsp width=100% scrolling=yes height=100%></IFRAME>";
		    text1 = "";
		}
		else {
		    link2 = "";
		    title = "Top Down ["+dt.getCurrentDate()+"]["+dt.getCurrentTime()+"]"+title_head_down;
		    text1 = "<HTML><HEAD><TITLE>Top Down Head</TITLE>"+
		    "</HEAD><BODY><CENTER>"+
		    "<H3>This is a computer generated top down stock list</H3>"+
		    "<TABLE width=50%>"+
		    "<TR><TD>Top down</TD><TD>"+dt.getCurrentDate()+"</TD>"+
		    "<TD>"+dt.getCurrentTime()+"</TD></TR>"+
		    "<TR><TD>Price range </TD><TD>"+start_price_down+"</TD><TD>"+end_price_down+"</TD></TR>"+
		    "<TR><TD>Volume range</TD><TD>"+v_low_limit+"</TD><TD>"+v_up_limit+"</TD></TR>"+
		    "<TR><TD>Number of results</TD><TD>"+numb_results+"</TD><TD></TD></TR>"+
		    "<TR><TD>Exchange</TD><TD>"+exchange+"</TD><TD></TD></TR>"+
		    "</TABLE></CENTER></BODY></HTML>";
		}
	    }
	}
	*/
	return sbf;
    }

    public boolean getTopUpListData () {

	String url_return_string = null;
	Vector url_return_vector1      = new Vector(10);

	setUrl("https://custom.marketwatch.com/custom/ameritrade2/screener/screener.asp?"+
			   "sh=1%2C1%2C1%2C1%2C1%2C1%2C1&pg=vop&cols=0&cols=4&cols=8&cols=1&"+
			   "cols=5&cols=9&cols=2&cols=6&cols=10&cols=3&cols=7&sort=4&sortd=0&"+
			   "numresults="+numb_results+"&s1=1&s1p1="+start_price_up+"&s1p2="+
			   end_price_up+"&s2=1&"+
			   "s2p1=0&s2p2=0.01&s2p3=0&s4p2=0&s9=1&s9p1="+v_low_limit+
			   "&s9p2="+v_up_limit+"&exchange="+exchange+"&result.x=45&result.y=15");
	
	//connectToUrl();
	//url_return_string  = getUrlReturnString();
	//stringToVector(url_return_string);
	//url_return_vector1  = getUrlReturnVector();
	//url_return_vector1  = selectUsefulInfo (url_return_vector1);
	//setRecord(url_return_vector1, "up");
	return true;
    }

    public boolean getTopDownListData () {
	String url_return_string = null;
        Vector url_return_vector2      = new Vector(10);
	setUrl("https://custom.marketwatch.com/custom/ameritrade2/screener/screener.asp?"+
			   "sh=1%2C1%2C1%2C1%2C1%2C1%2C1&pg=vop&cols=0&cols=4&cols=8&cols=1&"+
			   "cols=5&cols=9&cols=2&cols=6&cols=10&cols=3&cols=7&sort=4&sortd=1&"+
			   "numresults="+numb_results+"&s1=1&s1p1="+start_price_down+"&s1p2="+
			   end_price_down+"&s2=1&"+
			   "s2p1=1&s2p2=0.01&s2p3=0&s4p2=0&s9=1&s9p1="+v_low_limit+
			   "&s9p2="+v_up_limit+"&exchange="+exchange+"&result.x=45&result.y=11");
	
	//connectToUrl();
	//url_return_string = getUrlReturnString();
	//stringToVector(url_return_string);
	//url_return_vector2 = getUrlReturnVector();
	//url_return_vector2 = selectUsefulInfo (url_return_vector2);
	//setRecord(url_return_vector2,"down");
	return true;
    }

    public void setUrl (String url) {
	myUrl = url;
	process_message.append(myUrl+"<BR>");
    }

    /*
    private void setRecord (Vector v, String up_down) {

	int m =0;
	String temp [] = {"","","","","","","","","","",""};
	Vector record_vector = new Vector ();

	String sector_id = null;
	String sector_name = null;
	String industry_id = null;
	String industry_name = null;
	Hashtable sector_id_h = new Hashtable();
	Hashtable sector_name_h = new Hashtable();
	Hashtable industry_id_h = new Hashtable();
	Hashtable industry_name_h = new Hashtable();

	DataBaseQuery db1 = new DataBaseQuery ();

	String db_qr_str = null;
	db_qr_str = "SELECT * FROM tick";

	db1.setTickTableHashtable(db_qr_str, "Tick","Sector_Id");
	sector_id_h = db1.getTickTableHashtable();

	DataBaseQuery db2 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db2.setTickTableHashtable(db_qr_str, "Tick", "Sector_Name");
	sector_name_h = db2.getTickTableHashtable();

	DataBaseQuery db3 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db3.setTickTableHashtable(db_qr_str, "Tick", "Industry_Id");
	industry_id_h = db3.getTickTableHashtable();

	DataBaseQuery db4 = new DataBaseQuery ();

	db_qr_str = "SELECT * FROM tick";

	db4.setTickTableHashtable(db_qr_str, "Tick", "Industry_Name");
	industry_name_h = db4.getTickTableHashtable();

	Enumeration penum = v.elements();
	while ( penum.hasMoreElements()) {

	    temp[m] = (String)penum.nextElement();
	    m++;

	    if (m==11)  {

		StockRecord record = new StockRecord ();

		if (temp[0].equals("Symbol")) {
		    sector_id     = "Sector ID";
		    sector_name   = "Sector Name";
		    industry_id   = "Industry ID";
		    industry_name = "Industry Name";
		}
		else {
		    sector_id     = (String)sector_id_h.get(temp[0]);
		    sector_name   = (String)sector_name_h.get(temp[0]);
		    industry_id   = (String)industry_id_h.get(temp[0]);
		    industry_name = (String)industry_name_h.get(temp[0]);

		    if (sector_name == null || sector_id == null) {
			
			if (!newTickVector.contains(temp[0])) {
			    newTickVector.addElement(temp[0]);
			}

			sector_id   = "130";
			sector_name = "Unknow";
			industry_id   = "130";
			industry_name = "Unknow";
		    }
		}

		record.setTick    (temp[0]);
		record.setName    (temp[1]);
		record.setPrice   (temp[2]);
		record.setChange  (temp[3]);
		record.setPercent (temp[4]);
		record.setVolume  (temp[5]);
		record.setTime    (temp[6]);	
		record.setHigh    (temp[7]);
		record.setLow     (temp[8]);
		record.setPeratio (temp[9]);
		record.setMarkCap (temp[10]);
		record.setSectorId  (sector_id);
		record.setSectorName(sector_name);
		record.setIndustryId  (industry_id);
		record.setIndustryName(industry_name);

		record_vector.addElement(record);
		m=0;
	    }
	}

	if (up_down.equals("up")) {
	    setRecordVectorUp(record_vector);
	}
	else if (up_down.equals("down")) {
	    setRecordVectorDown(record_vector);
	}
    }
    */

    public Vector getRecordVectorUp() {
	return (recordVectorUp);
    }

    public Vector getRecordVectorDown() {
	return (recordVectorDown);
    }
    public void setRecordVectorUp(Vector v) {
	recordVectorUp = v;
    }
    public void setRecordVectorDown(Vector v) {
	recordVectorDown = v;
    }
    private void stringToVector (String input) {
	Vector url_return_vector = new Vector ();
	String element = "";
	StringTokenizer tokens = new StringTokenizer(input, "\n");
	while (tokens.hasMoreTokens()) {
	    element = tokens.nextToken();
	    url_return_vector.addElement(element);
	}

	setUrlReturnVector(url_return_vector);
    }

    public Vector getUrlReturnVector() {
	return urlReturnVector;
    }

    public void setUrlReturnVector(Vector v) {
	urlReturnVector = v;
    }
    
    private Vector sortRecordVector(Vector inputV) {
	int total = 0;
	
	Vector out_v = new Vector ();
	/*
	StockRecord record = new StockRecord ();
	StockRecord temp_record = new StockRecord ();

	Enumeration enum1 = inputV.elements();
	while ( enum1.hasMoreElements()) {
	    record = (StockRecord)enum1.nextElement();

	    Enumeration enum2 = inputV.elements();
	    while ( enum2.hasMoreElements()) {
		temp_record = (StockRecord)enum2.nextElement();
		if ((temp_record.getSectorName()).equals(record.getSectorName())){
		    if (!out_v.contains(temp_record)) {
			out_v.addElement(temp_record);
		    }
		}		
	    }
	}
	*/
	return out_v;
    }
}
